import { Injectable } from '@angular/core';
import { RestService, PagedResultDto } from '@abp/ng.core';
import { Observable, BehaviorSubject } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

// DTO 和 Filter 定义
export interface OtherWarehousing {
  id: string;
  creatorName: string;
  creationTime: Date;
  orderNo: string;
  ownerCode: string;  // 货主编码
  platform: number;   // 月台
  carNo: string;     // 车号
  driverName: string;  // 司机
  driverPhone: string;  // 司机电话
  status: string;     // 单据状态
  shipper: string;    // 货主
  estimatedArrivalTime: Date;  // 预计到达时间
  customerOrderNo: string;    // 客户订单号
  transportNo: string;       // 运输编号
  transportCompany: string;  // 运输公司名称
  supplier: string;         // 供应商名称
  reservedWarehouseArea: number;  // 预约库区
  warehouse: number;        // 仓库名称
  orderType: number;       // 订单类型
  remarks: string;         // 备注信息
  attachmentPath: string;  // 附件存储路径
  items: OtherWarehousingItemDto[];  // 入库单明细
}

// 搜索过滤条件
export interface OtherWarehousingFilter {
  maxResultCount?: number;
  skipCount?: number;
  sorting?: string;
  purchaseOrderNo?: string;
  ownerCode?: string;  // 货主编码
  orderType?: number;  // 订单类型
  customerOrderNo?: string;
  carNo?: string;
  driverName?: string;
  driverPhone?: string;
  expectedArrivalDateFrom?: string;
  expectedArrivalDateTo?: string;
  status?: string;
  platform?: number;
}

/**
 * 创建其它入库单的明细 DTO
 */
export interface OtherWarehousingItemDto {
  productCode: string;
  productName?: string;
  sku?: string;
  barcode?: string;
  specification?: string;
  brand?: string;
  quantity: number | null;
  plannedStorageSlots: number | null;
  status: 'Initial' | 'Yes' | 'No';
}

/**
 * 创建其它入库单的主体 DTO
 */
export interface OtherWarehousingCreateDto {
  orderNo: string;
  ownerCode: string;
  platform?: number;
  customerOrderNo: string;
  carNo?: string;
  driverName?: string;
  driverPhone?: string;
  status: string;
  shipper?: string;
  transportNo?: string;
  transportCompany?: string;
  supplier?: string;
  estimatedArrivalTime?: string;
  reservedWarehouseArea?: number;
  warehouse?: number;
  orderType?: number;
  remarks?: string;
  attachmentPath?: string;
  items: OtherWarehousingItemDto[];
}

// 下拉选项接口
export interface SelectOption {
  id: number;
  name: string;
  displayName?: string;
  value?: number;
  text?: string;
}

export interface SelectResponse {
  items: SelectOption[];
  totalCount: number;
}

@Injectable({
  providedIn: 'root'
})
export class OtherWarehousingService {
  apiName = 'Default';

  // 添加刷新机制
  private refreshSubject = new BehaviorSubject<boolean>(false);
  refresh$ = this.refreshSubject.asObservable();

  constructor(private restService: RestService) {}

  // 触发刷新的方法
  triggerRefresh() {
    this.refreshSubject.next(true);
  }

  create(input: OtherWarehousingCreateDto): Observable<OtherWarehousing> {
    return this.restService.request<any, OtherWarehousing>({
      method: 'POST',
      url: '/api/app/otherwarehousing-services',
      body: input
    });
  }

  getById(id: string): Observable<OtherWarehousing> {
    return this.restService.request<any, OtherWarehousing>({
      method: 'GET',
      url: `/api/app/otherwarehousing-services/${id}`
    });
  }

  getList(input: { skipCount: number; maxResultCount: number; sorting?: string }): Observable<PagedResultDto<OtherWarehousing>> {
    return this.restService.request<void, PagedResultDto<OtherWarehousing>>({
      method: 'GET',
      url: '/api/app/otherwarehousing-services',
      params: input,
    });
  }

  // 按条件查询
  getListByConditions(
    input: OtherWarehousingFilter & { skipCount: number; maxResultCount: number; sorting?: string }
  ): Observable<PagedResultDto<OtherWarehousing>> {
    console.log('Query params:', input);  // 添加日志
    return this.restService.request<any, PagedResultDto<OtherWarehousing>>({
      method: 'GET',
      url: '/api/app/otherwarehousing-services/by-conditions',
      params: input
    }).pipe(
      map(response => {
        console.log('API response:', response);  // 添加日志
        return response;
      }),
      catchError(error => {
        console.error('API error:', error);  // 添加错误日志
        throw error;
      })
    );
  }

  delete(id: string): Observable<void> {
    return this.restService.request<any, void>({
      method: 'DELETE',
      url: `/api/app/otherwarehousing-services/${id}`
    });
  }

  // 获取订单类型下拉选项
  getOrderTypes(): Observable<SelectResponse> {
    return this.restService.request<any, SelectResponse>({
      method: 'GET',
      url: '/api/app/otherwarehousing-services/order-type-model'
    }).pipe(
      map(response => {
        console.log('订单类型原始响应:', response);
        if (!response) {
          return { items: [], totalCount: 0 };
        }
        // 确保每个选项都有 value 和 name 属性
        const items = response.items?.map(item => ({
          ...item,
          value: item.value ?? item.id,
          name: item.name ?? item.displayName
        })) || [];
        return { items, totalCount: items.length };
      }),
      catchError(error => {
        console.error('获取订单类型失败:', error);
        throw error;
      })
    );
  }

  // 获取月台下拉选项
  getPlatforms(): Observable<SelectResponse> {
    return this.restService.request<any, SelectResponse>({
      method: 'GET',
      url: '/api/app/otherwarehousing-services/platform-dto-model'
    }).pipe(
      map(response => {
        console.log('月台原始响应:', response);
        if (!response) {
          return { items: [], totalCount: 0 };
        }
        // 确保每个选项都有 value 和 name 属性
        const items = response.items?.map(item => ({
          ...item,
          value: item.value ?? item.id,
          name: item.name ?? item.displayName
        })) || [];
        return { items, totalCount: items.length };
      }),
      catchError(error => {
        console.error('获取月台失败:', error);
        throw error;
      })
    );
  }

  // 获取预约库区下拉选项
  getWarehouseAreas(): Observable<SelectResponse> {
    return this.restService.request<any, SelectResponse>({
      method: 'GET',
      url: '/api/app/otherwarehousing-services/reserved-warehouse-area-model'
    }).pipe(
      map(response => {
        console.log('预约库区原始响应:', response);
        if (!response) {
          return { items: [], totalCount: 0 };
        }
        // 确保每个选项都有 value 和 name 属性
        const items = response.items?.map(item => ({
          ...item,
          value: item.value ?? item.id,
          name: item.name ?? item.displayName ?? item.text
        })) || [];
        return { items, totalCount: items.length };
      }),
      catchError(error => {
        console.error('获取预约库区失败:', error);
        throw error;
      })
    );
  }

  // 获取仓库下拉选项
  getWarehouses(): Observable<SelectResponse> {
    return this.restService.request<any, SelectResponse>({
      method: 'GET',
      url: '/api/app/otherwarehousing-services/warehouse-model'
    }).pipe(
      map(response => {
        console.log('仓库原始响应:', response);
        if (!response) {
          return { items: [], totalCount: 0 };
        }
        // 确保每个选项都有 value 和 name 属性
        const items = response.items?.map(item => ({
          ...item,
          value: item.value ?? item.id,
          name: item.name ?? item.displayName ?? item.text
        })) || [];
        return { items, totalCount: items.length };
      }),
      catchError(error => {
        console.error('获取仓库失败:', error);
        throw error;
      })
    );
  }
} 